import cv2
import numpy as np
import os

def crop_photo(path, target, solve_type):
    img = cv2.imread(path)
    height,width = img.shape[0:2]
#     if width > 1024:
#         img = cv2.resize(img, (1024, int(height/width*1024)), interpolation = cv2.INTER_AREA)
    # Load the cascade face detection model
    face_cascade = cv2.CascadeClassifier(os.path.dirname(__file__) + '/haarcascade_frontalface_default.xml')
    face = detect_single_face(face_cascade,img)
    im_face = crop_face(img, face, solve_type)
    cv2.imwrite(target, im_face)

def detect_single_face(face_cascade,img):
    # Convert into grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Detect faces
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)
    if(len(faces)==0):
        # print("Warming: no face detection, the portrait u2net will run on the whole image!")
        raise Exception("未检测到人脸")

    # filter to keep the largest face
    wh = 0
    idx = 0
    for i in range(0,len(faces)):
        (x,y,w,h) = faces[i]
        if(wh<w*h):
            idx = i
            wh = w*h

    return faces[idx]

def crop_face(img, face, solve_type):
    if(face is None):
        return img
    (x, y, w, h) = face

    w_length = 177/100*w
    h_length = 248/(h/w*100)*h
    center_x = x+int(w/2)
    center_y = y+int(h/2)
    left = int(center_x-w_length/2)
    right = int(center_x+w_length/2)
    top = int(center_y-h_length/2)
    bottom = int(center_y+h_length/2)
    height,width = img.shape[0:2]
    top_size, bottom_size, left_size, right_size = 0, 0, 0, 0
    if(left<0):
        left_size = -left
        left = 0
#         raise Exception("人脸左侧空间不够")

    if(right>width):
        right_size = right-width
        right = width
#         raise Exception("人脸右侧空间不够")

    if(top<0):
        top_size = -top
        top = 0
#         raise Exception("人脸上侧空间不够")

    if(bottom>height):
        bottom_size = bottom-height
        bottom = height
#         raise Exception("人脸下侧空间不够")

    im_face = img[top:bottom,left:right]
    im_face = cv2.copyMakeBorder(im_face,top_size,bottom_size,left_size,right_size,cv2.BORDER_CONSTANT,value=(0,0,0))
    if(solve_type=='speed'):
        im_face = cv2.resize(im_face, (177, 248), interpolation = cv2.INTER_AREA)

    return im_face
